from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from inc.models import DatabaseConfig, SystemConfig, OperationLog, db
from admin.admin.admin_class import DatabaseConfigForm, SystemConfigForm


admin_config_bp = Blueprint('admin_config', __name__)

@admin_config_bp.route('/database-config', methods=['GET', 'POST'])
@login_required
def database_config():
    form = DatabaseConfigForm()
    configs = DatabaseConfig.query.all()
    active_config = DatabaseConfig.query.filter_by(is_active=True).first()
    if form.validate_on_submit():
        try:
            if form.is_active.data:
                DatabaseConfig.query.update({DatabaseConfig.is_active: False})
                db.session.commit()
            config = DatabaseConfig(
                db_type=form.db_type.data,
                host=form.host.data,
                port=form.port.data,
                username=form.username.data,
                password=form.password.data,
                database=form.database.data,
                is_active=form.is_active.data
            )
            db.session.add(config)
            db.session.commit()
            log = OperationLog(
                admin_id=current_user.id,
                action="更新数据库配置",
                resource="DatabaseConfig",
                details=f"添加/更新数据库配置: {config.db_type} - {config.database}",
                success=True,
                ip_address=request.remote_addr
            )
            db.session.add(log)
            db.session.commit()
            flash('数据库配置已保存', 'success')
            return redirect(url_for('admin.admin_config.database_config'))
        except Exception as e:
            db.session.rollback()
            flash(f'保存数据库配置时出错: {str(e)}', 'danger')
    return render_template('admin/admin/admin_dateconfig.html',
                           form=form,
                           configs=configs,
                           active_config=active_config)

@admin_config_bp.route('/database-config/delete/<int:id>')
@login_required

def delete_database_config(id):
    config = DatabaseConfig.query.get_or_404(id)
    if config.is_active:
        flash('不能删除激活的数据库配置', 'danger')
        return redirect(url_for('admin.admin_config.database_config'))
    try:
        db.session.delete(config)
        log = OperationLog(
            admin_id=current_user.id,
            action="删除数据库配置",
            resource="DatabaseConfig",
            details=f"删除数据库配置: {config.db_type} - {config.database}",
            success=True,
            ip_address=request.remote_addr
        )
        db.session.add(log)
        db.session.commit()
        flash('数据库配置已删除', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'删除数据库配置时出错: {str(e)}', 'danger')
    return redirect(url_for('admin.admin_config.database_config'))

@admin_config_bp.route('/system-config', methods=['GET', 'POST'])
@login_required

def system_config():
    from inc.config_manager import SystemConfigManager
    config = SystemConfigManager.get_config()
    form = SystemConfigForm(obj=config)
    if form.validate_on_submit():
        try:
            SystemConfigManager.update_config(
                site_name=form.site_name.data,
                site_title=form.site_title.data,
                site_keywords=form.site_keywords.data,
                site_description=form.site_description.data,
                company_name=form.company_name.data,
                company_address=form.company_address.data,
                contact_phone=form.contact_phone.data,
                contact_email=form.contact_email.data,
                footer_info=form.footer_info.data,
                icp_number=form.icp_number.data,
                operation_log_enabled=form.operation_log_enabled.data
            )
            OperationLog.create(
                admin_id=current_user.id,
                action="更新系统配置",
                resource="SystemConfig",
                details="更新系统全局配置",
                success=True,
                ip_address=request.remote_addr
            )
            flash('系统配置已成功更新', 'success')
            return redirect(url_for('admin.admin_config.system_config'))
        except Exception as e:
            OperationLog.create(
                admin_id=current_user.id,
                action="更新系统配置",
                resource="SystemConfig",
                details=f"配置更新失败: {str(e)}",
                success=False,
                ip_address=request.remote_addr
            )
            flash(f'配置更新失败: {str(e)}', 'danger')
    return render_template('admin/admin/admin_system.html', form=form)

@admin_config_bp.route('/system-config/delete/<int:id>')
@login_required

def delete_system_config(id):
    config = SystemConfig.query.get_or_404(id)
    try:
        db.session.delete(config)
        OperationLog.create(
            admin_id=current_user.id,
            action="删除系统配置",
            resource="SystemConfig",
            details=f"删除系统配置: {config.config_key}",
            success=True,
            ip_address=request.remote_addr
        )
        db.session.commit()
        flash('系统配置已删除', 'success')
    except Exception as e:
        db.session.rollback()
        OperationLog.create(
            admin_id=current_user.id,
            action="删除系统配置",
            resource="SystemConfig",
            details=f"删除系统配置失败: {str(e)}",
            success=False,
            ip_address=request.remote_addr
        )
        flash(f'删除系统配置时出错: {str(e)}', 'danger')
    return redirect(url_for('admin.admin_config.system_config'))